#!/bin/bash

# Search for available HEX files to flash
declare -a HEX_ARRAY
HEX_ARRAY=("unused" `find out -name *.hex`)

# Check that there is at least one file to flash
if [ "${HEX_ARRAY[1]}" = "" ]; then
 echo "No HEX files found, please run ./build before !"
 exit 1
fi

# Read last file flashed for default value
if [ -e .flash ]; then
 DEFAULT=`cat .flash`
 if [ ! -e "$DEFAULT" ]; then
  DEFAULT=""
 fi
else
 DEFAULT=""
fi

# Display list
(( i=1 ))
while [ "${HEX_ARRAY[i]}" != "" ]; do
 if [ "$DEFAULT" = "${HEX_ARRAY[i]}" ]; then
  echo -n "* "
 else
  echo -n "  "
 fi
 echo "$i: `basename ${HEX_ARRAY[i]}`"
 (( i=i+1 ))
done

# Prompt user
read -p "Please select the HEX file to flash: [*] "
if [ "$REPLY" = "" ]; then
 HEX="$DEFAULT"
else
 HEX="${HEX_ARRAY[$REPLY]}"
fi
if [ ! -e "$HEX" ]; then
 echo "Invalid selection"
 exit 1
fi

# Save new default value
echo "$HEX" > .flash

# Flash
avrdude -c stk500v1 -p m328p -b 57600 -P /dev/ttyUSB0 -D -U "flash:w:${HEX}:i"
